import store from '@/store'
import TIM from 'tim-js-sdk';
//import TIMUploadPlugin from 'tim-upload-plugin'; //上传文件插件，暂时用不到
import { genUserSig } from "@/utils/common/generate-usersig.js"; //用户签名计算

var tim = null; // SDK 实例通常用 tim 表示
//sdk ready
const onSdkReady = () => {
	console.log('ready');
	// 更新IMSDK状态
	store.commit("UPDATE_IMSTATUS", true);
	if(store.state.isLogin){
		store.dispatch('updateBarNotice');
	}
};
//sdk noready
const onSdkNotReady = () => {
	store.commit("UPDATE_IMSTATUS", false);
};
//KickedOut 被顶下线
const onKickedOut = () => {
	store.dispatch("redirectLogin");
};
//会话未读总数更新 0916
const onTotalUnreadMessageCountUpdated = (event) => {
	// 当前单聊和群聊会话的未读总数
	store.commit("UPDATE_UNREADMSG", event.data);
};
//收到新消息
const onMessageReceived = (event) => {
	// 包含 Conversation 实例的数组
	store.commit("UPDATE_NEWMSG", event.data);
};
//tim init
const imInit = (imAppId) => {
	return new Promise((resolve,reject)=>{
		if(tim === null){
			try{
				const options = {
					SDKAppID: Number(imAppId) //即时通信 IM 应用的 SDKAppID
				}
				// 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
				tim = TIM.create(options); // SDK 实例通常用 tim 表示
				
				// 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
				//tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
				tim.setLogLevel(1); // release级别，SDK 输出关键信息，生产环境时建议使用
				
				// 注册腾讯云即时通信 IM 上传插件
				//tim.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});
				//返回
				resolve(tim)
			}catch(e){
				reject(e)
			}
		}else{
			resolve(tim)
		}
	})
};
const imMessage = {
	TIM: TIM,
	init: imInit,
	tim: () => {
		return tim
	},
	login: (userInfo={}) => {
		return new Promise((resolve,reject)=>{
			if(!store.state.imReady){
				// 开始登录
				if(!userInfo.userId){
					userInfo = store.state.user
				}
				imInit(userInfo.imAppId).then((tim) =>{
					//sdk ready
					tim.on(TIM.EVENT.SDK_READY, onSdkReady);
					//sdk noready
					tim.on(TIM.EVENT.SDK_NOT_READY, onSdkNotReady);
					//KickedOut 被顶下线
					tim.on(TIM.EVENT.KICKED_OUT, onKickedOut);
					//会话未读总数更新 0916
					tim.on(TIM.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, onTotalUnreadMessageCountUpdated);
					//收到新消息
					tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
					
					console.log('im login');
					// 开始登录
					let config = genUserSig(userInfo.userId, userInfo.imAppId, userInfo.imSecret)
					tim.login({
						userID: userInfo.userId, 
						userSig: config.userSig
					}).then((imResponse) => {
						console.log(imResponse.data,'login success'); // 登录成功
						resolve(true)
					}).catch((imError) => {
						console.warn('login error:', imError); // 登录失败的相关信息
						reject(imError)
					});
				}).catch((imError) => {
					console.warn('login error:', imError); // 初始化失败的相关信息
					reject(imError)
				})
			}else{
				console.log('ready');
				resolve(true)
			}
		})
	},
	sendTextMsg: (toUserId, textMsg) => {
		return new Promise((resolve,reject)=>{
			if(!store.state.imReady){
				console.log('sdk no ready');
				reject('sdk no ready')
			}else{
				// 1. 创建消息实例，接口返回的实例可以上屏
				let message = tim.createTextMessage({
					to: toUserId, //接收者ID
					conversationType: TIM.TYPES.CONV_C2C, //会话类型，取值TIM.TYPES.CONV_C2C（端到端会话）或TIM.TYPES.CONV_GROUP（群组会话）
					payload: {
						text: textMsg, //文字消息内容
					}
				});
				console.log(message);
				// 2. 发送消息
				tim.sendMessage(message).then((imResponse) => {
					// 发送成功
					console.log(imResponse);
					resolve(imResponse)
				}).catch((imError) => {
					// 发送失败
					console.warn('sendMessage error:', imError);
					reject(imError)
				});
			}
		})
	},
	sendImageMsg: (toUserId, imageMsg) => {
		return new Promise((resolve,reject)=>{
			if(!store.state.imReady){
				console.log('sdk no ready');
				reject('sdk no ready')
			}else{
				// 1. 创建消息实例，接口返回的实例可以上屏
				let message = tim.createImageMessage({
					to: toUserId,
					conversationType: TIM.TYPES.CONV_C2C,
					payload: { file: imageMsg },
					onProgress: function(event) { 
						console.log('file uploading:', event) 
					}
				});
				console.log(message);
				// 2. 发送消息
				tim.sendMessage(message).then((imResponse) => {
					// 发送成功
					console.log(imResponse);
					resolve(imResponse)
				}).catch((imError) => {
					// 发送失败
					console.warn('sendMessage error:', imError);
					reject(imError)
				});
			}
		})
	},
	sendAudioMsg: (toUserId, audioFile) => {
		return new Promise((resolve,reject)=>{
			if(!store.state.imReady){
				console.log('sdk no ready');
				reject('sdk no ready')
			}else{
				// 1. 创建消息实例，接口返回的实例可以上屏
				let message = tim.createAudioMessage({
					to: toUserId,
					conversationType: TIM.TYPES.CONV_C2C,
					payload: { file: audioFile }
				});
				console.log(message);
				// 2. 发送消息
				tim.sendMessage(message).then((imResponse) => {
					// 发送成功
					console.log(imResponse);
					resolve(imResponse)
				}).catch((imError) => {
					// 发送失败
					console.warn('sendMessage error:', imError);
					reject(imError)
				});
			}
		})
	},
	sendVideoMsg: (toUserId, videoMsg) => {
		return new Promise((resolve,reject)=>{
			if(!store.state.imReady){
				console.log('sdk no ready');
				reject('sdk no ready')
			}else{
				// 1. 创建消息实例，接口返回的实例可以上屏
				let message = tim.createVideoMessage({
					to: toUserId,
					conversationType: TIM.TYPES.CONV_C2C,
					payload: { file: videoMsg },
					onProgress: function(event) { 
						console.log('file uploading:', event) 
					}
				});
				console.log(message);
				// 2. 发送消息
				tim.sendMessage(message).then((imResponse) => {
					// 发送成功
					console.log(imResponse);
					resolve(imResponse)
				}).catch((imError) => {
					// 发送失败
					console.warn('sendMessage error:', imError);
					reject(imError)
				});
			}
		})
	},
	sendCustomMsg: (toUserId, customMsg, description='自定义消息', extension='自定义消息') => {
		return new Promise((resolve,reject)=>{
			if(!store.state.imReady){
				console.log('sdk no ready');
				reject('sdk no ready')
			}else{
				// 1. 创建消息实例，接口返回的实例可以上屏
				let message = tim.createCustomMessage({
					to: toUserId, //接收者ID
					conversationType: TIM.TYPES.CONV_C2C, //会话类型，取值TIM.TYPES.CONV_C2C（端到端会话）或TIM.TYPES.CONV_GROUP（群组会话）
					payload: {
						data: customMsg,
						description, 
						extension
					}
				});
				console.log(message);
				// 2. 发送消息
				tim.sendMessage(message).then((imResponse) => {
					// 发送成功
					console.log(imResponse);
					resolve(imResponse)
				}).catch((imError) => {
					// 发送失败
					console.warn('sendMessage error:', imError);
					reject(imError)
				});
			}
		})
	},
	getMsgList: () => {
		return new Promise((resolve,reject)=>{
			// 拉取会话列表
			tim.getConversationList().then((imResponse) => {
				//const conversationList = imResponse.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
				resolve(imResponse)
			}).catch((imError) => {
				console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
				reject(imError)
			});
		})
	},
	getMsgInfo: (conversationID) => {
		return new Promise((resolve,reject)=>{
			// 获取会话资料
			tim.getConversationProfile(conversationID).then((imResponse) => {
				//console.log(imResponse.data.conversation); // 会话资料
				resolve(imResponse)
			}).catch((imError) => {
				console.warn('getConversationProfile error:', imError); // 获取会话资料失败的相关信息
				reject(imError)
			});
		})
	},
	getMsgInfoList: (conversationID, nextReqMessageID=null) => {
		return new Promise((resolve,reject)=>{
			if(!nextReqMessageID){
				// 打开某个会话时，第一次拉取消息列表
				tim.getMessageList({
					conversationID
				}).then((imResponse) => {
					//console.log(imResponse.data.messageList)
					resolve(imResponse)
				}).catch((imError) => {
					console.warn('getConversationProfile error:', imError); // 获取会话资料失败的相关信息
					reject(imError)
				});
			}else{
				// 下拉查看更多消息
				tim.getMessageList({
					conversationID,
					nextReqMessageID
				}).then((imResponse) => {
					console.log(imResponse.data.messageList)
					resolve(imResponse)
				}).catch((imError) => {
					console.warn('getConversationProfile error:', imError); // 获取会话资料失败的相关信息
					reject(imError)
				});
			}
		})
	},
	deleteConversation: (conversationID) => {
		return new Promise((resolve,reject)=>{
			// 删除会话
			tim.deleteConversation(conversationID).then((imResponse) => {
				// 删除会话成功
				//const { conversationID } = imResponse.data; // 被删除的会话 ID
				resolve(imResponse)
			}).catch((imError) => {
				console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
				reject(imError)
			});
		})
	},
	pinConversation: (conversationID, isPinned) => {
		return new Promise((resolve,reject)=>{
			// 置顶/取消置顶会话，v2.14.0起支持
			tim.pinConversation({ conversationID, isPinned }).then((imResponse) => {
				// 置顶会话成功
				//const { conversationID } = imResponse.data; // 被置顶的会话 ID
				resolve(imResponse)
			}).catch((imError) => {
				console.warn('pinConversation error:', imError); // 置顶会话失败的相关信息
				reject(imError)
			});
		})
	},
	setMessageRead: (conversationID) => {
		return new Promise((resolve,reject)=>{
			// 将某会话下所有未读消息已读上报
			tim.setMessageRead({ conversationID }).then((imResponse) => {
				// 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
				resolve(imResponse)
			}).catch((imError) => {
				console.warn('setMessageRead error:', imError);  // 已读上报失败
				reject(imError)
			});
		})
	},
	deleteMessage: (msgList) => {
		return new Promise((resolve,reject)=>{
			// 删除消息
			tim.deleteMessage(msgList).then(function(imResponse) {
				// 删除消息成功
				resolve(imResponse)
			}).catch(function(imError) {
				// 删除消息失败
				console.warn('deleteMessage error:', imError);
				reject(imError)
			});
		})
	},
	revokeMessage: (message) => {
		return new Promise((resolve,reject)=>{
			// 主动撤回消息
			tim.revokeMessage(message).then(function(imResponse) {
				// 消息撤回成功
				resolve(imResponse)
			}).catch(function(imError) {
				// 消息撤回失败
				console.warn('deleteMessage error:', imError);
				reject(imError)
			});
		})
	},
	updateMyProfile: () => {
		// 修改个人标配资料
		let user = store.state.user
		let options = {
			nick: user.nickname,
			gender: user.sex ? TIM.TYPES.GENDER_MALE : TIM.TYPES.GENDER_FEMALE
		}
		if( user.avatar ){
			options.avatar = user.avatar
		}
		if( user.birthday ){
			options.birthday = Number(user.brithday.substr(0, 10).replace(/\-/g, ''))
		}
		console.log(options);
		tim.updateMyProfile({
			...options
		}).then(function(imResponse) {
			console.log(imResponse.data); // 更新资料成功
		}).catch(function(imError) {
			console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
		});
	},
	logout: () => {
		tim.logout().then((imResponse) => {
			console.log('im logout');
			//sdk ready
			tim.off(TIM.EVENT.SDK_READY, onSdkReady);
			//sdk noready
			tim.off(TIM.EVENT.SDK_NOT_READY, onSdkNotReady);
			//KickedOut 被顶下线
			tim.off(TIM.EVENT.KICKED_OUT, onKickedOut);
			//会话未读总数更新 0916
			tim.off(TIM.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, onTotalUnreadMessageCountUpdated);
			//收到新消息
			tim.off(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
			//tim恢复初始值
			tim = null
			store.commit("UPDATE_IMSTATUS", false)
		}).catch((imError) => {
			console.warn('logout error:', imError);
		});
	},
	destroy: () => {
		tim.destroy().then(() => {
			console.log('sdk destroyed');
			//tim恢复初始值
			tim = null
			store.commit("UPDATE_IMSTATUS", false)
		}).catch((imError) => {
			console.warn('destroy error:', imError);
		});
	},
}

export default imMessage